<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/1/7
 * Time: 12:30
 */

namespace Xcx\Model;

class PhotoModel extends CommonModel
{

    public $errMsg;

    public function getErrMsg()
    {
        return $this->errMsg;
    }
    /**
     * 上传照片
     * @param $describe
     * @param $photo
     * @return mixed
     */
    public function uploadPhoto($describe, $photo)
    {
        $uid = $this->getUid();

        $data['uid'] = $uid;
        $data['describe'] = $describe;
        $data['photo'] = $photo;
        $data['add_time'] = time();

        return $this->data($data)->add();
    }

    /**
     * 获取照片墙列表
     * @return array|string
     */
    public function getPhotoList()
    {
        $list = $this->alias('a')
            ->field('a.*,b.nickname,b.header')
            ->join('left join t_users b on a.uid = b.id')
            ->where(array('a.state'=>'0'))
            ->order(array('add_time'=>'desc'))
            ->select();

        $list = getUploadImgDir($list,array('user_head'=>'header','photo'=>'photo'));
        return $list;
    }

    /**
     * 添加照片点赞数量
     * @param $pid
     * @param $count
     * @return bool
     */
    public function setIncPraiseCount($pid,$count = 1)
    {
        $maps['id'] = $pid;
        return $this->where($maps)->setInc('praise',$count);
    }

    /**
     * 根据照片的用户ID
     * @param $pid
     * @return mixed
     */
    public function getUidByPid($pid)
    {
        return $this->where(array('id'=>$pid))->getField('uid');
    }

    /**
     * 获取照片墙照片详细信息
     * @param $id
     * @return mixed
     */
    public function getPhotoDetails($id)
    {
        $data = $this->alias('a')
            ->field('a.*,b.nickname,b.header')
            ->join('left join t_users b on a.uid = b.id')
            ->where(array('a.id'=>$id))
            ->find();

        if ($data) {
            $data['header'] = getUploadImgDir($data['header'],'user_head');
            $data['photo'] = getUploadImgDir($data['photo'],'photo');
            $PraiseRecord = new PraiseRecordModel();
            $list = $PraiseRecord->getPraiseRecordList($id);
            $data['list'] = $list;
            $data['user_count'] = count($list);
            $data['is_praise'] = $PraiseRecord->checkUserIsPraise($id);
        }
        return $data;
    }

    /**
     * 用户点赞
     * @param $pid
     * @return bool
     */
    public function doPraise($pid)
    {
        M()->startTrans();
        $PraiseRecord = new PraiseRecordModel();
        if ($PraiseRecord->checkUserIsPraise($pid)) {
            $this->errMsg = '今日已完成点赞';
            return false;
        }
        $res1 = $PraiseRecord->addUserPraiseRecord($pid);
        if ($res1) {
            M()->commit();
            return true;
        } else {
            M()->rollback();
            return false;
        }
    }

}